package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BookOrderInfo;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.PayAndBackParams;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:农机组织在线接单
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/3/18 20:21
 */
public class OnlineReceiveOrderDetailFragment extends BaseOrderDetailFragment {
  private static final int REQUEST_PAY = 1;
  /**
   * 农机组织输入的接单信息
   */
  private EditText tvRemark;

  public static OnlineReceiveOrderDetailFragment newInstance(BookOrderInfo item) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_ITEM, item);
    OnlineReceiveOrderDetailFragment fragment = new OnlineReceiveOrderDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.orderDetail);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_confirm:
        //如果接单完成,不能再重复接单
        if (DataStatus.RECEIVE_PUBLISH.equals(mItem.getDataStatus())) {
          //ToastUtil.show("用户已确认订单,无法重复接单!");
          BaseConfirmDialogFragment.show(mActivity, "订单已经接单完成,无法重复接单!", "");
        } else {

          showConfirmDialog();
        }
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 显示确认接单对话框,提示接单保证金额,可以输入文本,
   */
  private void showConfirmDialog() {
    String bookDeposit = mItem.getBookDeposit();
    //noinspection deprecation
    final double bookDepositDouble = MyUtils.valueOfDouble(bookDeposit, 0);
    String hintMessage = "接单需要支付<font color='#FF0000'>" + bookDepositDouble + "元</font>,是否确认接单";
    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
    //builder.setIcon(android.R.drawable.ic_dialog_info);
    builder.setTitle(Html.fromHtml(hintMessage));
    tvRemark = new EditText(mActivity);
    tvRemark.setHint(R.string.hintInput);
    builder.setView(tvRemark);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {
        //如果预约保证金不为0,去支付预约保证金,否则直接提交
        if (bookDepositDouble > 0) {
          PayAndBackParams params = new PayAndBackParams();
          params.setId(UUID.randomUUID().toString());
          params.setMainId(mItem.getId());
          params.setPayMuch(String.valueOf(bookDepositDouble));
          params.setEditable(false);

          params.setMoneyType(PayAndBackParams.MONEY_TYPE_GARRENTEE_FEE);
          params.setBookOrderNo(mItem.getBookNo());
          params.setOrderType(PayAndBackParams.ORDER_TYPE_ORDER);
          PayAndBackActivity.newInstance(OnlineReceiveOrderDetailFragment.this,
              PayAndBackActivity.class, params, REQUEST_PAY);
        } else {

          volleyPostSubmit();
        }
      }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
      @Override public void onClick(DialogInterface dialog, int which) {

      }
    });
    builder.create().show();
  }

  private void volleyPostSubmit() {
    String id = mItem.getId();
    String text = tvRemark.getText().toString().trim();
    String memberCode = CurrentUser.newInstance(mActivity).getMemberCode();
    if (id == null || memberCode == null) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_RECEIVE_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", id);
    params.put("text", text);
    params.put("memberCode", memberCode);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        ToastUtil.show(original.getMessage());
        if (Base.SUCCESS == original.getResult()) {
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    switch (requestCode) {
      case REQUEST_PAY:
        //付款成功后.直接接单
        volleyPostSubmit();
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
